import React, { Component, useState } from 'react'
import Square from './Square'


export default function Board({xIsNext, squares, onPlay}) {

  const calculateWinner = (squares) => {
    const lines = [
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
      [0, 3, 6],
      [1, 4, 7],
      [2, 5, 8],
      [0, 4, 8],
      [2, 4, 6]
    ]
    let val = null
    lines.map((i, index) => {
      const [a, b, c] = i
      if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
        val =  squares[a];
      //  return squares[a];  错误: 在map内return 出去的是该循环内部的,并不会中断函数执行
      }
    })
   if (val) return val

    // 官方写法: 
    // for (let i = 0; i < lines.length; i++) {
    //   const [a, b, c] = lines[i];
    //   if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
    //     return squares[a];
    //   }
    // }
    return null
  }

  const handleClick = (i)=> {
    console.log('calculateWinner(squares)', calculateWinner(squares));
    if (squares[i] || calculateWinner(squares)) return
    const nextSquares = squares.slice()
    if (xIsNext) {
      nextSquares[i] = "X" 
    }else {
      nextSquares[i] = "O" 
    }
    onPlay(nextSquares)
  }

  const winner = calculateWinner(squares)
  let status = 'start'
  if (winner) {
    status = 'winner :' + winner
  }else {
    status = 'Next player:' + ( xIsNext ? 'X' : 'O')
  }

    return (
      <>
        <h2>井字游戏</h2>
        <h5>{status}</h5>
        <div className="board-row">
          <Square value={squares[0]} onSquareClick={() => handleClick(0)} />
          <Square value={squares[1]} onSquareClick={() => handleClick(1)} />
          <Square value={squares[2]} onSquareClick={() => handleClick(2)} />
        </div>
        <div className="board-row">
          <Square value={squares[3]} onSquareClick={() => handleClick(3)} />
          <Square value={squares[4]} onSquareClick={() => handleClick(4)} />
          <Square value={squares[5]} onSquareClick={() => handleClick(5)} />
        </div>
        <div className="board-row">
          <Square value={squares[6]} onSquareClick={() => handleClick(6)} />
          <Square value={squares[7]} onSquareClick={() => handleClick(7)} />
          <Square value={squares[8]} onSquareClick={() => handleClick(8)} />
        </div>
      </>
    )
}
